﻿using Model.Parameter.Admin;
using Model.Parameter.Front;
using Model.Result.Front;

namespace IService.Front
{
    public class CustomerService : BaseService<TCustomerinfo>, ICustomerService
    {
        private readonly JwtConfig _Config;
        private readonly WebMiscConfig _WebMiscConfig;
        private readonly IUploadService _Upload;

        public CustomerService(IUnitOfWorkService unitOfWorkService, IOptions<JwtConfig> con, IOptions<WebMiscConfig> webMiscConfig, IUploadService uploadService) : base(unitOfWorkService)
        {
            _Config = con.Value;
            _WebMiscConfig = webMiscConfig.Value;
            _Upload = uploadService;
        }

        public async Task<RM_FrontApiReturn<RM_Customerinfo>> BaseInfo()
        {
            var user = _CurrentCustomer;
            if (user != null)
            {
                // var result = user.Adapt<RM_Customerinfo>();
                var o = await _DbContext.Queryable<TCustomerinfo>().Select<RM_Customerinfo>().FirstAsync(o => o.Id == user.Id);

                return (_ResultHelper.BuildSuccess(o)).Adapt<RM_FrontApiReturn<RM_Customerinfo>>();
            }
            else
            {
                return (_ResultHelper.BuildError(Enum_SysAttributeType.Customer.NoLogin)).Adapt<RM_FrontApiReturn<RM_Customerinfo>>();
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> LoginByAccount(string account, string passWord)
        {
            //检查参数
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(passWord))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Misc.ParmaterError);
            }

            passWord = md5Helper.CalculateMD5Hash(passWord);
            //构建查询
            var where = Expressionable.Create<TCustomerinfo>().And(o => o.IsDeleted == false)
                .And(o => (o.Phone == account || o.Email == account) && o.Password == passWord);

            if (await Any(where.ToExpression()))
            {
                var result = new RM_Customer();
                var user = await Get(where.ToExpression());
                //清除用户之前的token，防止重复登录，以及本地token
                if (!string.IsNullOrEmpty(user.Token))
                {
                    _Redis.DeleteRedisAttr("en", user.Token, Enum_RedisKey.CustomerToken);
                }

                user.LastLoginDate = DateTime.Now;
                user.Token = Guid.NewGuid().ToString();
                user.ExpireTime = DateTime.Now.AddSeconds(_Config.ExpireTime);
                await Update(user, o => new { o.LastLoginDate, o.Token, o.ExpireTime });

                //添加redis缓存
                _Redis.SetRedisAttr("en", user.Token, user, (DateTime)user.ExpireTime, Enum_RedisKey.CustomerToken);

                result.User = user;

                return _ResultHelper.BuildActionSuccess(result);
            }
            else
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.LoginErrorByAccount);
            }
        }

        /// <summary>
        /// 退出登录，清除redis缓存，采用新返回格式
        /// </summary>
        /// <returns></returns>

        public async Task<RM_FrontApiReturn<object>> Logout()
        {
            //检查是否存在当前用户
            if (_CurrentCustomer != null)
            {
                //更新过期时间
                await Update(_CurrentCustomer, o => o.ExpireTime == DateTime.Now);

                //清除redis缓存
                _Redis.DeleteRedisAttr("en", _CurrentCustomer.Token, Enum_RedisKey.CustomerToken);
            }
            return (_ResultHelper.BuildSuccess()).Adapt<RM_FrontApiReturn<object>>();
        }

        public RM_ApiResult GetDefaultAvator()
        {
            var defaultAvator = AppSettings.GetConfig("WebMiscConfig:DefaultAvator");

            return _ResultHelper.BuildSuccess(defaultAvator);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="par"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<RM_ApiResult> RegisterCustomer(Par_Customerinfo1 par)
        {
            if (string.IsNullOrEmpty(par.NickName) || string.IsNullOrEmpty(par.Password))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Misc.ParmaterError);
            }
            if (!string.IsNullOrEmpty(par.Phone) && await Any(o => o.Phone == par.Phone && o.IsDeleted == false))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.PhoneExist);
            }
            if (!string.IsNullOrEmpty(par.Email) && await Any(o => o.Email == par.Email && o.IsDeleted == false))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.EmailExist);
            }
            if (string.IsNullOrEmpty(par.Email) && string.IsNullOrEmpty(par.Phone))
            {
                return _ResultHelper.BuildActionError(Enum_SysAttributeType.Customer.PhoneAndEmailEmpty);
            }

            //添加用户
            var tpar = par.Adapt<TCustomerinfo>();
            tpar.Password = md5Helper.CalculateMD5Hash(par.Password);
            //上传图片
            //检查文件

            if (string.IsNullOrEmpty(tpar.Avatar))
            {
                //获取配置的默认头像
                tpar.Avatar = _WebMiscConfig.DefaultAvator;
            }

            await ExecuteTransaction(async () =>
            {
                tpar.CreateTime = DateTime.Now;
                tpar.LastLoginDate = DateTime.Now;
                tpar.Token = Guid.NewGuid().ToString();
                tpar.ExpireTime = DateTime.Now.AddSeconds(_Config.ExpireTime);

                tpar.Phone = string.IsNullOrEmpty(par.Phone) ? "" : par.Phone;
                tpar.Email = string.IsNullOrEmpty(par.Email) ? "" : par.Email;
                tpar.Status = (int)Enum_BaseStatus.Working;
                tpar.IsDeleted = false;
                await Add(tpar);
            });

            return _ResultHelper.BuildActionSuccess();

            //添加redis缓存
            //_Redis.SetRedisAttr(par.Token, par, (DateTime)par.ExpireTime, Enum_RedisKey.CustomerToken);
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>

        public RM_ApiResult GetSexSelect()
        {
            return _ResultHelper.BuildSuccess(_EnumHelper.GetSelect4Enum<Enum_Sex>());
        }

        public RM_ApiResult GetSourceSelect()
        {
            return _ResultHelper.BuildSuccess(_EnumHelper.GetSelect4Enum<Enum_Source>());
        }

        #region 券包

        public async Task<RM_ApiResult> GetCouponList()
        {
            List<Img> list = new();
            var user = _CurrentCustomer;
            if (user != null)
            {
                var reqList = await _DbContext.Queryable<TRecycleReq>()

                   .Where(o => o.CustomerId == user.Id && o.Status == (int)Enum_RecycleStatus.Returned)
                   .OrderBy(o => o.CreateTime, OrderByType.Desc).ToListAsync();

                foreach (TRecycleReq req in reqList)
                {
                    var sendList = await _DbContext.Queryable<TRecycleSend>().Where(u => u.ReqId == req.Id).ToListAsync();
                    foreach (var send in sendList)
                    {
                        TRecycleSendHandle handle = await _DbContext.Queryable<TRecycleSendHandle>().Where(u => u.SendId == send.Id).OrderByDescending(o => o.Id).FirstAsync();

                        if (!string.IsNullOrEmpty(handle?.Coupon))
                        {
                            var imgs = handle.Coupon.FromJson<List<Img>>();
                            if (imgs?.Count > 0)
                            {
                                list.AddRange(imgs);
                            }
                        }
                    }
                }

                return _ResultHelper.BuildSuccess(list);
            }
            else
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Customer.NoLogin);
            }
        }

        public async Task<RM_ApiResult> UpdateCustomer(Par_Customerinfo par)
        {
            if (par.Id != _CurrentCustomer.Id)
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Customer.NoLogin);
            }
            var tpar = par.Adapt<TCustomerinfo>();

            var result = await Update(tpar, null, o => new { o.CreateTime, o.LastLoginDate, o.Token, o.ExpireTime, o.Password, o.Status, o.IsDeleted });

            if (result > 0)
            {
                return _ResultHelper.BuildSuccess();
            }
            else
            {
                return _ResultHelper.BuildError(Enum_SysAttributeType.Customer.NoLogin);
            }
        }

        #endregion 券包
    }

    public class Img
    {
        /// <summary>
        /// 图片名称
        /// </summary>
        public string name { get; set; }

        /// <summary>
        /// 图片地址
        /// </summary>
        public string url { get; set; }
    }
}